package handler

import (
	"encoding/json"
	"game-page-mgr/cache"
	"game-page-mgr/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CreateShop(c *gin.Context) {
	name := c.PostForm("name")
	num, _ := strconv.Atoi(c.PostForm("num"))
	content := c.PostForm("content")
	address := c.PostForm("address")
	if name == "" || address == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Shopping{
		Name:    name,
		Num:     num,
		Content: content,
		Address: address,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "create_" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func CreateShopClass(c *gin.Context) {
	sid, _ := strconv.Atoi(c.PostForm(c.PostForm("sid")))
	cid, _ := strconv.Atoi(c.PostForm(c.PostForm("cid")))

	data := model.ShopClass{
		Sid: sid,
		Cid: cid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ListShopClass(c *gin.Context) {

}

func ListShop(c *gin.Context) {
	var shop []model.Shopping

	redis_key := "list_"
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if errCount == "" {
		model.DB.Find(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(errCount), &shop)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取列表成功",
		"data": shop,
	})
	return

}

func DetailShop(c *gin.Context) {
	id := c.Query("id")
	var shop model.Shopping
	err := model.DB.Where("id=?", id).First(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "详情失败",
		})
		return
	}
	redis_key := "detail_" + id
	model.DB.Where("id=?", id).First(&shop)
	jsData, _ := json.Marshal(shop)

	cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": shop,
	})
	return
}
